[Cocoa] Binding CoreData Managed Object to NSTextFieldCell subclass

Posted by ndg on Stack Overflow See other posts from Stack Overflow or by ndg
Published on 2010-05-20T13:06:34Z Indexed on 2010/05/20 13:10 UTC
Read the original article Hit count: 330

I have an NSTableView which has its first column set to contain a custom NSTextFieldCell. My custom NSTextFieldCell needs to allow the user to edit a "desc" property within my Managed Object but to also display an "info" string that it contains (which is not editable). To achieve this, I followed this tutorial. In a nutshell, the tutorial suggests editing your Managed Objects generated subclass to create and pass a dictionary of its contents to your NSTableColumn via bindings.

This works well for read-only NSCell implementations, but I'm looking to subclass NSTextFieldCell to allow the user to edit the "desc" property of my Managed Object. To do this, I followed one of the articles comments, which suggests subclassing NSFormatter to explicitly state which Managed Object property you would like the NSTextFieldCell to edit. Here's the suggested implementation:

@implementation TRTableDescFormatter

- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error
{
    if (anObject != nil){
        *anObject = [NSDictionary dictionaryWithObject:string forKey:@"desc"];
        return YES;
    }
    return NO;
}
- (NSString *)stringForObjectValue:(id)anObject
{
    if (![anObject isKindOfClass:[NSDictionary class]]) return nil;
    return [anObject valueForKey:@"desc"];
}
- (NSAttributedString*)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attrs
{
    if (![anObject isKindOfClass:[NSDictionary class]]) return nil;
    NSAttributedString *anAttributedString = [[NSAttributedString alloc] initWithString: [anObject valueForKey:@"desc"]];

    return anAttributedString;
}

@end

I assign the NSFormatter subclass to my cell in my NSTextFieldCell subclass, like so:

- (void)awakeFromNib
{
    TRTableDescFormatter *formatter = [[[TRTableDescFormatter alloc] init] autorelease];
    [self setFormatter:formatter];
}

This seems to work, but is extremely patch. On occasion, clicking to edit a row will cause its value to nullify. On other occasions, the value you enter on one row will populate other rows within the table.

I've been doing a lot of reading on this subject and would really like to get to the bottom of this. What's more frustrating is that my NSTextFieldCell is rendering exactly how I would like it to. This editing issue is my last obstacle! If anyone can help, that would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about nstextfieldcell

Related posts about nstableview